<template>
	<view class="preview" v-if="currentInfo">
		<!-- 这边直接传了图片的索引，索引可以做到点那个是那个 -->
		<swiper circular class="swp" :current="currentIndex" @change="swiperChange">
			<swiper-item v-for="(item,index) in classList" :key="item._id" class="items">
				<image v-if="readImgs.includes(index)" @click="maskChange" :src="item.picurl" mode="aspectFill"
					class="imagess"></image>

			</swiper-item>
		</swiper>
		<!-- 存储已查看的缓存 -->

		<!-- 遮罩层 -->
		<view class="mask" v-if="maskState">
			<!-- 左上角的返回箭头 -->
			<view class="goBack" :style="{top:getTitleBarHeight()+15+'px'}" @click="goBack">
				<uni-icons type="back" color="#fff" size="20"> </uni-icons>
			</view>
			<view class="count">
				{{currentIndex+1}} / {{classList.length}}
			</view>
			<view class="time">
				<!-- 一般用法 -->
				<uni-dateformat :date="new Date()" format="hh:mm"></uni-dateformat>
			</view>
			<view class="date">

				<!-- 一般用法 -->
				<uni-dateformat :date="new Date()" format="MM月dd日"></uni-dateformat>
			</view>
			<view class="footer" >
				<view class="box" @click="clickInfo">
					<uni-icons type="info" size="28">

					</uni-icons>
					<view class="text">
						信息
					</view>
				</view>
				<view class="box" @click="clickScore">
					<uni-icons type="star" size="28">

					</uni-icons>
					<view class="text">
						{{currentInfo.score}}分
					</view>
				</view>
				<view class="box" @click="clickDownload">
					<uni-icons type="download" size="23">

					</uni-icons>
					<view class="text">
						下载
					</view>
				</view>
			</view>
		</view>
		<!-- 这是官方的插件，需要导入的  这是个弹窗-->
		<uni-popup ref="infoPopup" type="bottom">
			<view class="infoPopup">
				<!-- 上下俩部分 -->

				<view class="popHeader">
					<view>
						<!-- 这个是空盒子 -->
					</view>
					<view class="title">
						壁纸信息
					</view>
					<!-- 关闭按钮 -->
					<view class="close" @click="clickInfoClose">
						<uni-icons type="closeempty" size="18" color="#999"></uni-icons>
					</view>
				</view>
				<!-- 增加滚动条 垂直方向-->
				<scroll-view scroll-y>
					<view class="content" >
						<!-- 这里面有很多组件嵌套 -->
						<view class="row">
							<text class="label">
								壁纸ID：
							</text>
							<!-- 文本可选 -->
							<text selectable class="value">{{currentInfo._id}}</text>
						</view>
						<!-- <view class="row" >
							<text class="label">
								分类：
							</text>
							
							<text selectable class="value class">明星美女</text>
						</view> -->

						<view class="row">
							<text class="label">
								发布者：
							</text>
							<!-- 文本可选 -->
							<text selectable class="value">{{currentInfo.nickname}}</text>
						</view>
						<view class="row">
							<text class="label">
								评分：
							</text>
							<view class="value roteBox">
								<!-- 小星星添加了 只读 和不允许滑动 -->
								<uni-rate readonly touchable :value="currentInfo.score" size="16" />
								<text selectable class="score">{{currentInfo.score}}</text>
							</view>

						</view>
						<view class="row">
							<text class="label">
								摘要：
							</text>
							<!-- 文本可选 -->
							<text class="value">{{currentInfo.description}}</text>
						</view>

						<view class="row">
							<text class="label">
								标签：
							</text>
							<view class="value tabs">
								<!-- 文本可选 -->
								<view class="tab" v-for="tab in currentInfo.tabs" key="tab">{{tab}}</view>
							</view>

						</view>
						<view class="copyright">
							声明：本图片来源于用户投稿，非商业使用，用于免费交流学习，如侵犯了您的权益，您可以拷贝壁纸ID举报至平台，邮箱2801535837@qq.com，管理员将删除侵权壁纸，维护您的权益。

						</view>
							<!-- 去注释掉官方的安全区域样式，修改成自己的安全区域样式 -->
							<view class="safe-area-inset-bottom">
								
							</view>
					</view>

				</scroll-view>
			</view>
		</uni-popup>

		<!-- 评分的弹窗  这个必须点那个打叉才能关闭所以给了false-->
		<uni-popup ref="socerPopup" :is-mask-click="false">
			<view class="socerPopup">
				<!-- 头部 -->
				<view class="popHeader">
					<view>
						<!-- 这个是空盒子 -->
					</view>
					<!-- 这边做一个三元表达式 -->
					<view class="title">
						{{isScore?'评分过了':'壁纸评分'}}
					</view>
					<!-- 关闭按钮 -->
					<view class="close" @click="clickScoreClose">
						<uni-icons type="closeempty" size="18" color="#999"></uni-icons>
					</view>
				</view>
				<!-- 主体 -->
				<view class="content">
					<uni-rate v-model="userScore" allowHalf :disabled="isScore" disabled-color="#FFCA3E" />
					<text class="text">{{userScore}} 分</text>
				</view>
				<!-- 底部 -->
				<view class="footer">
					<!-- 按钮状态禁用，根据评分的数量来决定，如果是0那就禁用 -->
					<button @click="submitScore" :disabled="!userScore || isScore" type="default" size="mini" plain>确认评分
					</button>
				</view>

			</view>
		</uni-popup>

	</view>
</template>

<script lang="ts" setup>
	import { apiGetSetupScore, apiWriteDownload,apiDetailWall } from "@/api/apis.js";
	import { ref } from 'vue';
	import { getTitleBarHeight } from "@/utils/system.js";
	import { onLoad,onShareAppMessage,onShareTimeline } from "@dcloudio/uni-app";
	/* 默认显示 ref响应式显示数据 */
	const maskState = ref(true);
	const infoPopup = ref(null);
	const socerPopup = ref(null);
	const userScore = ref(0);
	const classList = ref([]);
	const currentId = ref(null);
	const currentIndex = ref(0);
	/* 定一个看过的图作为变量 */
	const readImgs = ref([]);
	/* 存储每个图片的信息 */
	const currentInfo = ref(null);
	/* 把_small.webp替换成jpg就行了 */
	//获取网页缓存,缓存如果没数据就返回一个空数组
	const isScore = ref(false);




	const storgClassList = uni.getStorageSync("storgClassList") || [];
	//将缓存数组进行一个替换操作，把后缀改成jpg大图的格式
	classList.value = storgClassList.map(item => {
		// ...先把数据展开
		return {
			...item,
			picurl: item.smallPicurl.replace("_small.webp", ".jpg")
		}
	})
	console.log(classList.value)


	/* 点击信息弹窗  open（）是直接打开（官网写的）*/
	const clickInfo = () => {
		infoPopup.value.open();
	}
	/* 这个是关闭信息弹窗，看官网，和上面那个对应 */
	const clickInfoClose = () => {

		infoPopup.value.close();
	}
	//评分弹窗
	const clickScore = () => {
		if (currentInfo.value.userScore) {
			isScore.value = true
			userScore.value = currentInfo.value.userScore;
		}
		socerPopup.value.open();
	}
	//关闭评分弹窗
	const clickScoreClose = () => {
		socerPopup.value.close();
		/* 关闭弹窗后初始化星星的评级 */
		userScore.value = 0;
		isScore.value = false;
	}

	//遮罩状态
	/* 点击后变成false 再点击又变回来true */
	const maskChange = () => {
		maskState.value = !maskState.value;
	}

	//确认评分
	const submitScore = async () => {
		/* 在这边加一个网络的加载,没有请求完就转圈圈 */
		uni.showLoading({
			title: "加载钟..."
		})
		console.log("提交评分了~~~~")
		/* 解构方式去弄 */
		let { classid, _id: wallId } = currentInfo.value

		let res = await apiGetSetupScore({
			classid,
			wallId,
			userScore: userScore.value
		});

		uni.hideLoading();
		if (res.errCode === 0) {
			uni.showToast({
				title: "评分成功",
				icon: "none"
			})
			/* 评分之后增加一个数据源userScore,然后添加数据进去 */
			classList.value[currentIndex.value].userScore = userScore.value;
			/* 更新缓存 数据源*/
			uni.setStorageSync("storgClassList", classList.value);
			/* 评分成功后关闭弹窗 */
			clickScoreClose();
		}

		console.log(res);

	}
	/* 返回上一页 */
	const goBack = () => {
		/* 关闭当前这层页面,返回上一层页面 ,下面那个是跳转回到首页的房子*/
		uni.navigateBack({
			success:()=>{
				
			},fail:(err)=> {
				uni.reLaunch({
					url:"/pages/index/index"
				})
			}
		})
	}
	/* 拿id用 进图片当索引,用户分享单张壁纸给好友或者朋友圈，好友只能查看一张照片*/
	onLoad(async(e) => {
		currentId.value = e.id;
		if(e.type == 'share'){
			let res = await apiDetailWall({id:currentId.value});
			classList.value = res.data.map(item=>{
				return {
					...item,
					picurl: item.smallPicurl.replace("_small.webp", ".jpg")
				}
			})
		}
		console.log("输出一下索引值" + currentId.value)
		/* 获取数据下的索引值 */
		currentIndex.value = classList.value.findIndex(item => item._id == currentId.value)
		/* 图片信息调取,应用 */
		currentInfo.value = classList.value[currentIndex.value]
		readImgsFun();

	})


	const swiperChange = (e) => {
		/* 在图片里面滑动的时候修改上面的页面索引值,就是当时是XX/总数 这样子 */
		currentIndex.value = e.detail.current;
		/* 图片信息调取,应用 */
		currentInfo.value = classList.value[currentIndex.value]

		/* 看过的图片 */
		readImgsFun();
	}

	function readImgsFun() {
		/* 看过的图片,加载的时候左右两侧一起加载，一次加载三张 */
		readImgs.value.push(
			currentIndex.value <= 0 ? classList.value.length - 1 : currentIndex.value - 1,
			currentIndex.value,
			currentIndex.value >= classList.value.length - 1 ? 0 : currentIndex.value + 1
		);
		/* 网页会有很多重复的索引,所以这边要做一个去重的操作 */
		/* new Set可以保证唯一对象,然后通过...把数据展开就是正常的数组了 */
		readImgs.value = [...new Set(readImgs.value)];
	}

	
	//点击下载
	const clickDownload = async () => {

		// #ifdef H5
		uni.showModal({
			content: "请长按保存壁纸",
			showCancel: false
		})
		// #endif

		// #ifndef H5
		try {

			uni.showLoading({
				title: "下载中...",
				mask: true
			})
			let {
				classid,
				_id: wallId
			} = currentInfo.value;
			let res = await apiWriteDownload({
				classid,
				wallId
			})
			if (res.errCode != 0) throw res;
			uni.getImageInfo({
				src: currentInfo.value.picurl,
				success: (res) => {
					uni.saveImageToPhotosAlbum({
						filePath: res.path,
						success: (res) => {
							uni.showToast({
								title: "保存成功，请到相册查看",
								icon: "none"
							})
						},
						fail: err => {
							if (err.errMsg == 'saveImageToPhotosAlbum:fail cancel') {
								uni.showToast({
									title: '保存失败，请重新点击下载',
									icon: "none"
								})
								return;
							}
							uni.showModal({
								title: "授权提示",
								content: "需要授权保存相册",
								success: res => {
									if (res.confirm) {
										uni.openSetting({
											success: (setting) => {
												console.log(
													setting);
												if (setting
													.authSetting[
													'scope.writePhotosAlbum'
												]) {
													uni.showToast({
														title: "获取授权成功",
														icon: "none"
													})
												} else {
													uni.showToast({
														title: "获取权限失败",
														icon: "none"
													})
												}
											}
										})
									}
								}
							})
						},
						complete: () => {
							uni.hideLoading();
						}
					})

				}
			})

		} catch (err) {
			console.log(err);
			uni.hideLoading();
		}
		// #endif
	}
	
	//分享给好友,这个是分享的函数nShareAppMessage 官方的.
		onShareAppMessage((e) => {
			return {
				title: "王同学的壁纸库",
				path: "pages/preview/preview?id="+currentId.value+"&type=share"
			}
		})
		//分享朋友圈 需要权限，要不就是用小程序测试号的appid
		//测试号id是wx04394c05eeb40715
		//主号用的是wxd4651c59239cb9b7
		onShareTimeline(() => {
			return {
				title: "王同学的壁纸库",
				query:"id="+currentId.value
			}
		})
	
	
	
	
	
</script>




<style lang="scss" scoped>
	.preview {
		width: 100%;
		height: 100vh;
		position: relative;

		.swp {
			width: 100%;
			height: 100%;

			.items {
				width: 100%;
				height: 100%;

				.imagess {
					width: 100%;
					height: 100%;

				}
			}

		}

		.mask {

			/* 这个代表父级紧邻的view元素下面的box孙子元素不受影响 */
			&>view {
				position: absolute;
				width: fit-content;
				/* 根据内容给大小 */
				left: 0;
				margin: auto;
				color: #fff;
				right: 0;
			}

			.goBack {
				width: 38px;
				height: 38rpx;
				background: rgba(0, 0, 0, 0.5);
				left: 30rpx;
				margin-left: 0;
				border-radius: 100rpx;
				top: 0;
				backdrop-filter: blur(10rpx);
				border: 1rpx solid rgba(255, 255, 255, 0.3);
				display: flex;
				align-items: center;
				justify-content: center;
			}

			.count {
				top: 10vh;
				background: rgba(0, 0, 0, 0.3);
				font-size: 28rpx;

				border-radius: 40rpx;
				padding: 8rpx 28rpx;
				/* 模糊效果 */
				backdrop-filter: blur(10rpx);
			}

			.time {
				font-size: 140rpx;
				top: calc(10vh + 80rpx);
				/* 计算公式,以10为基准,向下移动80 */
				font-weight: 100;
				/* 文字粗细 */
				line-height: 1em;
				/* 把行高去掉 */
				text-shadow: 0 4rpx rgba(0, 0, 0, 0.3);
				/* 文字阴影 */
			}

			.date {
				font-size: 34rpx;
				top: calc(10vh + 230rpx);
				/* 计算公式,以10为基准,向下移动230 */
				text-shadow: 0 2rpx rgba(0, 0, 0, 0.3);
				/* 文字阴影 */
				color: #fff;


			}

			.footer {
				/* 以低为基准往上平移10vh然后用flex布局居中平分空间,外型做了120的圆角胶囊设计,黑色字体,背景浅灰透明0.8 */
				background: rgba(255, 255, 255, 0.8);
				bottom: 10vh;
				/* 以低为基准去调整位置. */
				width: 65vw;
				height: 100rpx;
				border-radius: 120rpx;
				color: #000;
				display: flex;
				justify-content: space-around;
				align-items: center;
				box-shadow: 0 2rpx 0 rgba(0, 0, 0, 0.1);
				/* 边框阴影 */
				/* 模糊效果 */
				backdrop-filter: blur(20rpx);

				.box {
					display: flex;
					flex-direction: column;
					align-items: center;
					justify-content: center;
					padding: 2rpx 10rpx;

					.text {
						font-size: 26rpx;
						color: $text-font-color2;

					}
				}
			}
		}

		.popHeader {
			display: flex;
			justify-content: space-between;
			/* 因为上面有写了个空盒子，所以是三份直接平分 */
			align-items: center;

			.title {
				color: $text-font-color2;
				font-size: 26rpx;
			}

			/* 触摸区域 */
			.close {
				padding: 6rpx;
			}
		}

		.infoPopup {
			background: #fff;
			padding: 30rpx;
			border-radius: 30rpx 30rpx 0 0;
			overflow: hidden;
			/* 内容溢出隐藏并且滚动条 */

			/* 弹框的最大高度 */
			scroll-view {
				max-height: 60vh;

				/* 父级 */
				.content {
					.row {
						display: flex;
						padding: 16rpx 0;
						font-size: 32rpx;
						line-height: 1.7em;

						.label {
							color: $text-font-color3;
							width: 140rpx;
							text-align: right;
							font-size: 30rpx;

						}

						.value {
							flex: 1;
							width: 0;
							/* 兼容性写法,以防太大 */
						}

						.roteBox {
							display: flex;
							align-items: center;

							.score {
								font-size: 26rpx;
								color: $text-font-color2 ;
								padding-left: 10rpx;
							}
						}

						.tabs {
							display: flex;
							flex-wrap: wrap;

							.tab {
								border: 1px solid $brand-theme-color;
								color: $brand-theme-color;
								font-size: 22rpx;
								padding: 10rpx 30rpx;
								border-radius: 40rpx;
								line-height: 1em;
								margin: 0 10rpx 10rpx 0;

							}

						}

						.class {
							color: $brand-theme-color;

						}

					}

					.copyright {
						font-size: 28rpx;
						padding: 20rpx;
						background: #F6F6F6;
						color: #666;
						border-radius: 10rpx;
						margin: 20rpx 0;
						line-height: 1.6em;

					}

				}
			}


		}

		.socerPopup {
			background: #fff;
			padding: 30rpx;
			width: 70vw;
			border-radius: 30rpx;

			.content {
				padding: 30rpx 0;
				/* 上下30左右0 */
				display: flex;
				justify-content: center;
				align-items: center;

				.text {
					/* 评分后的颜色 */
					color: #FFCA3E;
					padding-left: 10rpx;
					width: 80rpx;
					line-height: 1em;
					text-align: right;

				}
			}

			.footer {
				padding: 10rpx 0;
				display: flex;
				justify-content: center;
				align-items: center;

			}
		}
	}
</style>